package com.zhuhaibaoxian.wanjiuseller.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhuhaibaoxian.wanjiuseller.IView.IListView;
import com.zhuhaibaoxian.wanjiuseller.R;
import com.zhuhaibaoxian.wanjiuseller.adapter.MyRecycleViewAdapter;
import com.zhuhaibaoxian.wanjiuseller.app.MyApplication;
import com.zhuhaibaoxian.wanjiuseller.bean.ReceiveListBean;
import com.zhuhaibaoxian.wanjiuseller.bean.RemarkBean;
import com.zhuhaibaoxian.wanjiuseller.bean.SureListBean;
import com.zhuhaibaoxian.wanjiuseller.interfacewj.GetListPresenter;
import com.zhuhaibaoxian.wanjiuseller.utils.Constants;
import com.zhuhaibaoxian.wanjiuseller.utils.ExampleUtil;
import com.zhuhaibaoxian.wanjiuseller.utils.LogUtil;
import com.zhuhaibaoxian.wanjiuseller.utils.ToastUtil;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WeiWanChengActivity extends AppCompatActivity implements IListView {

    @Bind(R.id.toolbar_title)
    TextView toolbarTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.tab)
    TabLayout tab;
    @Bind(R.id.recyclerview)
    XRecyclerView recyclerview;
    @Bind(R.id.viewpager)
    ViewPager viewpager;
    @Bind(R.id.btn_update)
    Button btnUpdate;
    @Bind(R.id.tv_num)
    TextView tvNum;
    private GetListPresenter getListPresenter;
    private BuildBean buildBean;
    public static boolean isForeground = false;
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        recyclerview.setLoadingMoreEnabled(false);
        getListPresenter = new GetListPresenter(this);
        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData(recyclerview);
            }

            @Override
            public void onLoadMore() {

            }
        });
        getData(recyclerview);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        registerMessageReceiver();  // used for receive msg

    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    private void setCostomMsg(String msg) {
        LogUtil.e("msg = " + msg);
    }

    private void getData(XRecyclerView recyclerview) {
        buildBean = DialogUIUtils.showLoading(WeiWanChengActivity.this, "加载中...", false, true, true, true);
        buildBean.show();
        getListPresenter.getList(recyclerview, buildBean);

    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void getDataSuccess(final ReceiveListBean value) {
        if (value.getData() != null && value.getData().getW().size() > 0) {
            tvNum.setText(""+value.getData().getW().size());
            recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            //noinspection unchecked
            recyclerview.setAdapter(new MyRecycleViewAdapter(value.getData().getW(), R.layout.item_paidlist, this, false) {
                @Override
                protected void setPositionClick(int position) {
                }

                @Override
                protected void initData(MyViewHolder holder, int position) {
                    List<ReceiveListBean.DataBeanXX.WBean> w = value.getData().getW();
                    setHolderData(w, holder, position);
                }

            });
            recyclerview.refreshComplete();
            DialogUIUtils.dismiss(buildBean);

        } else {
            DialogUIUtils.dismiss(buildBean);
            ToastUtil.showLong(MyApplication.context, "没有订单哦！");
        }

    }

    @Override
    public void sureSuccess(SureListBean value) {
        getData(recyclerview);
    }

    @Override
    public void getRemarkSuccess(RemarkBean value) {

    }

    private void setHolderData(final List<ReceiveListBean.DataBeanXX.WBean> w, final MyRecycleViewAdapter.MyViewHolder holder, final int position) {
        if (w != null && w.size() > 0) {
            holder.getTextView(R.id.tv_order).setText(w.get(position).getOrder_mun() == null ? "" : w.get(position).getOrder_mun());//订单号
            holder.getTextView(R.id.tv_time).setText(w.get(position).getTime_end() == null ? "" : w.get(position).getTime_end());//交易时间
            holder.getTextView(R.id.jian).setText((w.get(position).getMun() == 0 ? 0 : w.get(position).getMun()) + "");//商品总数量
            holder.getTextView(R.id.tb_price).setText("￥" + (w.get(position).getTotal() == null ? "" : w.get(position).getTotal()));//订单总价
            holder.getTextView(R.id.tv_arrive_time).setText(w.get(position).getArrive_end() == null ? "" : w.get(position).getArrive_end());//送达时间
            holder.getTextView(R.id.tv_address).setText(w.get(position).getAddress() == null ? "" : w.get(position).getAddress().replace("\\n", "\n"));//送达地址
            holder.getTextView(R.id.tv_beizhu).setText(w.get(position).getRemarks() == null ? "" : w.get(position).getRemarks());//订单备注
            holder.getTextView(R.id.tv_jifen).setText("积分：" + (w.get(position).getIntegral() == null ? "" : w.get(position).getIntegral()));//积分
            holder.getTextView(R.id.tv_phone).setText((w.get(position).getLogin_id() == null ? "" : w.get(position).getLogin_id()));//电话

            holder.getTextView(R.id.tv_phone).setOnClickListener(new View.OnClickListener() {//打电话
                @Override
                public void onClick(View v) {
                    Intent intent1 = new Intent(Intent.ACTION_DIAL);
                    intent1.setData(Uri.parse("tel:" + holder.getTextView(R.id.tv_phone).getText().toString()));
                    startActivity(intent1);
                }
            });
            holder.getTextView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {//确认订单
                @Override
                public void onClick(View v) {
                    new AlertDialog
                            .Builder(WeiWanChengActivity.this)
                            .setTitle("确认订单")
                            .setMessage("是否确定订单：" + w.get(position).getOrder_mun())
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    getListPresenter.sureOrder(w.get(position).getOrder_mun());
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            })
                            .create()
                            .show();
                }
            });
            RecyclerView recyclerView1 = (RecyclerView) holder.getView(R.id.recyclerview);
            recyclerView1.setNestedScrollingEnabled(false);
            recyclerView1.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            final List<ReceiveListBean.DataBeanXX.WBean.DataBean> data1 = w.get(position).getData();

            if (data1 != null && data1.size() > 0) {
                //noinspection unchecked
                recyclerView1.setAdapter(new MyRecycleViewAdapter(data1, R.layout.item_paidimg, this, false) {
                    @Override
                    protected void setPositionClick(int position) {
//                      ToastUtil.showShort(MyApplication.context,"posi="+data1.get(position).getGoods_id());
                    }

                    @Override
                    protected void initData(MyViewHolder holder, int position) {
                        String img = Constants.QIPAIMG1 + data1.get(position).getGoods_id() + "/" + data1.get(position).getPhoto_first_name();
                        holder.bindImage(R.id.iv, img);//图片
                        holder.getTextView(R.id.tv_name).setText(data1.get(position).getName() == null ? "" : data1.get(position).getName());//名字
                        holder.getTextView(R.id.tv_price).setText("￥:" + (data1.get(position).getPrice() == null ? "" : data1.get(position).getPrice()));//价钱 = 单价*数量
                        holder.getTextView(R.id.tv_num).setText(data1.get(position).getNum() == null ? "" : data1.get(position).getNum());//数量
                        holder.getTextView(R.id.tv_unit).setText(data1.get(position).getUnit() == null ? "" : data1.get(position).getUnit());//单位
                    }

                });
            }

        }
    }

    @OnClick(R.id.btn_update)
    public void onViewClicked() {
        getData(recyclerview);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMessageReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        }
    }
}
